const md5 = require('blueimp-md5');
const chalk = require('chalk');
const fetch = require('isomorphic-fetch');

const params = {
  headers: {
    'content-type': 'application/x-www-form-urlencoded;charset=UTF-8',
  },
  method: "POST",
  // agent: new https.Agent({
  //   rejectUnauthorized: false
  // }),
  body: null
};

const mapi = 'https://api.dev.pajkdc.com/m.api';


function req(data) {
  let encryptdata = encrypt(data, false);
  delete encryptdata._mt;

  console.log(chalk.bgYellow('[encryptdata]'), encryptdata);
  
  let p = Object.assign({},  params);

  p.body = serialize(encryptdata);

  console.log(chalk.bgBlue('[params]'), p);
  return fetch(mapi + `?_mt=${data._mt}`, p)
      .then(function(response) {
        if (response.status >= 400) {
            console.log(chalk.red("Bad response from server"), response);
            throw new Error("Bad response from server");
        }
        return response.json();
    }).then(function(stories) {
        console.log(chalk.bgGreen('[stories]'), stories);
    });
}


function serialize(obj, prefix) {
  const str = [];
  for (let p in obj) {
    if (obj.hasOwnProperty(p)) {
      const k = prefix ? `${prefix}[${p}]` : p;
      const v = obj[p];

      str.push(`${encodeURIComponent(k)}=${encodeURIComponent(v)}`);
    }
  }
  return str.join('&');
};


function encrypt(data, userLogin = false) {
  const wtkStr = getHash(userLogin);
  let mergedParams = Object.assign({
      '_sm': 'md5'
    }, data),
    paramStringList = [],
    keys = [];
  Object
    .keys(mergedParams)
    .forEach(key => {
      keys.push(key);
    });
  keys.sort();
  keys.forEach(key => {
    if (typeof mergedParams[key] !== 'undefined') {
      paramStringList.push('' + key + '=' + mergedParams[key]);
    }
  });
  console.log('wtkStr', wtkStr);
  paramStringList.push(wtkStr);

  mergedParams._sig = md5(paramStringList.join(''));
  return mergedParams;
}

function getHash(userLogin) {
  if (!userLogin) {
    return 'jk.pingan.com';
  } else {
    return '67d5dd45bc3c0817ee64ded24a7ff0cb';
  }
}

module.exports = {
  getHash,
  req,
  serialize
};